"use strict";
const moment = require('moment');

function getProperty( obj, key, defaultValue=0 ){
    let ret = obj? ( obj[key] || defaultValue ) : defaultValue;
    return  typeof(ret) == "number"? parseFloat(ret.toFixed(2)):ret;
}

//**********
function dictByKey(arr,key){
    let ret = [];
    arr.forEach((i)=>{
        ret[i[key]] = i;
    })
    return ret;
}

function getType(v){
    return Object.prototype.toString.call(v).match(/\[object (\w+)\]/)[1];
}

function isEqual( a, b ){
    let typeA = getType(a) ;
    let typeB = getType(b);
    switch( typeA+typeB ){
    case 'ObjectObject':
        let arrKeys = Object.keys( a );
        if( arrKeys.length == Object.keys(b).length ){
            return arrKeys.every( v => isEqual( a[v], b[v] ) );
        }
        else{
            return false;
        }
        break;
    case 'StringDate':
    case 'DateString':
        return moment(a).unix() == moment(b).unix();
        break;
    case 'ArrayArray':
        return a.length == b.length && a.join() == b.join();
        break;
    default:
        return a == b;
    }
}

module.exports = {
    getProperty,
    dictByKey,
    isEqual
}
